package com.jinxin.platform.cdacscontrolmgr.task;

import com.jinxin.platform.cdacscontrolmgr.bean.CdacscontrolmgrRegistInfo;
import com.jinxin.platform.cdacscontrolmgr.common.Constant;
import com.jinxin.platform.cdacscontrolmgr.redis.CdacscontrolmgrRedisUtil;
import com.jinxin.platform.cdacscontrolmgr.service.ICdacscontrolkmgrRegistInfoService;
import com.jinxin.platform.cdacscontrolmgr.service.impl.CdacscontrolkmgrRegistInfoServiceImpl;
import com.jinxin.platform.cdacscontrolmgr.utils.DateUtil;
import com.jinxin.platform.cdacscontrolmgr.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-07-09
 * @Author: Lingnan
 **/
@Slf4j
public class SchedulerQuartzJob implements Job {

    private final CdacscontrolmgrRedisUtil cdacscontrolmgrRedisUtil =
            (CdacscontrolmgrRedisUtil) SpringContextUtils.getBeanByClass(CdacscontrolmgrRedisUtil.class);
    private final ICdacscontrolkmgrRegistInfoService registInfoService =
            (ICdacscontrolkmgrRegistInfoService) SpringContextUtils.getBeanByClass(CdacscontrolkmgrRegistInfoServiceImpl.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobKey jobKey = context.getJobDetail().getKey();
        String registId = jobKey.getName();
        CdacscontrolmgrRegistInfo registInfo = registInfoService.getById(registId);
        if(registInfo == null){
            log.error("已到访客访问时间,未查询到登记信息");
            return;
        }
        String visitDate = registInfo.getVisitDate();
        String leaveTime = registInfo.getLeaveTime();
        String tempPwd = registInfo.getTempPwd();
        if(StringUtils.isEmpty(visitDate) || StringUtils.isEmpty(leaveTime) || StringUtils.isEmpty(tempPwd)){
            log.error("登记信息的到访时间和离开时间未填");
            return;
        }
        String dateStr = visitDate.trim() + " " + leaveTime.trim();
        Date endDate = DateUtil.string2Date(dateStr);
        long seconds = DateUtil.getDifferSeconds(new Date(), endDate);
        // 将登记记录id作为key,后续输入密码的时候根据mac对应的项目id及用户输入的密码反查访客登记记录，
        // 再结合redis中密码是否过期进行判断是否开门
        cdacscontrolmgrRedisUtil.set(registId, tempPwd,seconds);
    }
}
